package geektime.spring.springbucks.mapper;

import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.model.CoffeeOrder;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;


@Mapper
public interface CoffeeOrderMapper {

    @Insert("insert into t_order (create_time, update_time, customer, state)"
            + "values (now(), now(), #{customer}, #{state})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int saveOrder(CoffeeOrder order);

    @Insert("<script>" +
            "insert into t_order_coffee (coffee_order_id, items_id)"
            + "values"
            + "<foreach collection=\"items\" index=\"index\" item=\"item\" separator=\",\"> "
            + "(#{id}, #{item.id})"
            + "</foreach>"
            + "</script>")
    int saveCoffeeOrder(CoffeeOrder order);

    @Update("update t_order set state = #{state} where id = #{id} ")
    void update(CoffeeOrder order);

    @Select("select * from t_order where id = #{id}")
     @Results({
             @Result(id = true, column = "id", property = "id"),
             @Result(column = "{id = id}", property = "items", many = @Many(select = "geektime.spring.springbucks.mapper.CoffeeOrderMapper.findCoffeeByOrderId"))
     })
    CoffeeOrder findById(@Param("id") Long id);

    @Select("select * from t_order order by id")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "{id = id}", property = "items", many = @Many(select = "geektime.spring.springbucks.mapper.CoffeeOrderMapper.findCoffeeByOrderId"))
    })
    List<CoffeeOrder> findAll();

    @Select("select * from t_order_coffee t1 inner join t_coffee t2 on t1.items_id = t2.id where t1.coffee_order_id = #{id} order by t2.id")
    List<Coffee> findCoffeeByOrderId();
}
